<template>
  <div>
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片区域 -->
      <el-card class="box-card">
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="addRoleVisible=true">添加角色</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table
          :data="rolesList"
          style="width: 100%"
          border
          stripe
        >
          <el-table-column type="expand">
            <template v-slot="roleChildren">
              <!-- 先渲染一级菜单 -->
              <el-row :class="['b_bottom', i === 0 ? 'b_top' : '','vcenter']" v-for="(item_1,i) in roleChildren.row.children" :key="item_1.id">
                <el-col :span="5">
                  <el-tag type="primary">{{item_1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <!-- 渲染2级菜单 -->
                  <el-row :class="[i2 === 0 ? '' : 'b_top','vcenter']" v-for="(item_2,i2) in item_1.children" :key="item_2.id">
                    <el-col :span="6">
                      <el-tag type="success">{{item_2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染3级菜单 -->
                    <el-col :span="18">
                      <el-tag type="warning" closable v-for="item_3 in item_2.children" :key="item_3.id">{{item_3.authName}}</el-tag>
                    </el-col>
                 </el-row >
                </el-col>
              </el-row >
            </template>
          </el-table-column>
          <el-table-column
            label="#"
            type="index">
          </el-table-column>
          <el-table-column
            prop="roleName"
            label="角色名称">
          </el-table-column>
          <el-table-column
            prop="roleDesc"
            label="角色描述">
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="mySlot">
              <el-button @click="editDialog(mySlot.row.id)" type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button @click="delDialog(mySlot.row)" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button @click="treeDialog(mySlot.row)" type="warning" icon="el-icon-setting">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
        <!--添加角色的弹出框-->
        <el-dialog title="添加角色" v-model="addRoleVisible" width="50%">
          <!--ref 类似于dom操作获取节点，这里获取此表单-->
          <el-form :model="roleForm" status-icon :rules="rules" ref="roleForm" class="demo-ruleForm" label-width="80px">
            <el-form-item label="角色名称" prop="username">
              <el-input v-model="roleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="roleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
              <span class="dialog-footer">
                <el-button @click="resetForm('roleForm')">取 消</el-button>
                <el-button type="primary" @click="addRole('roleForm')">确 定</el-button>
              </span>
          </template>
        </el-dialog>

        <!-- 删除角色操作 -->
        <el-dialog
          title="删除角色"
          v-model="delRoleVisible"
          width="30%"
          center>
          <span>你确定要删除{{roleName}}用户吗?</span>
          <template #footer>
          <span class="dialog-footer">
            <el-button @click="delRoleVisible = false">取 消</el-button>
            <el-button type="primary" @click="del">确 定</el-button>
          </span>
          </template>
        </el-dialog>

        <!-- 编辑角色操作 -->
        <el-dialog
          title="编辑角色"
          v-model="editRoleVisible"
          width="50%"
          center>
          <el-form :model="updateForm" status-icon :rules="rules" ref="updateForm" class="demo-ruleForm" label-width="90px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="updateForm.roleName"  disabled></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="updateForm.roleDesc" ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
          <span class="dialog-footer">
            <el-button @click="editRoleVisible = false">取 消</el-button>
            <el-button type="primary" @click="edit">确 定</el-button>
          </span>
          </template>
        </el-dialog>

        <!-- 权限管理弹出框 -->
        <el-dialog
          title="分配权限"
          v-model="showTreeVisible"
          width="50%"
          :before-close="handleClose">

          <!--树-->
          <el-tree
            :data="treeList"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="checkArr"
            :props="treeProps"
            ref="treeRef">
          </el-tree>

          <template #footer>
          <span class="dialog-footer">
            <el-button @click="showTreeVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRoleInfo">确 定</el-button>
          </span>
          </template>
        </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
name: "roles",
  data(){
    return{
      rolesList:[],
      addRoleVisible:false,
      delRoleVisible: false,
      editRoleVisible:false,
      showTreeVisible:false,
      treeList:[],
      checkArr:[],
      treeProps:{
        label:'authName',//到时候treeList里面的authName这个字段，作为树节点的内容
        children:'children'
      },
      role_id:0,
      roleForm:{
        roleName:'',
        roleDesc:''
      },
      updateForm:{

      },
      rules:{
        roleName: [
          { required: true, message:'请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message:'请输入角色描述', trigger: 'blur' }
        ]
      },
      roleName: ''
    }
  },
  created() {
    this.getAllRoles();
  },
  methods:{
    //获取所有的用户数据
    getAllRoles(){
      this.axios.get(`roles`).then(resp=>{
        console.log()
        this.rolesList = resp.data.data;
        //console.log(this.rolesList);
      }).catch(err=>{
        console.log(err);
      })
    },

    //编辑角色
    editDialog(id){
      this.role_id = id;
      this.editRoleVisible = true;
      this.axios.get(`roles/${this.role_id}`).then(resp=>{
        //console.log(resp.data.data);
        this.updateForm = resp.data.data
      }).catch(err=>{
        console.log(err);
      })
    },
    edit(){
      this.axios.put(`roles/${this.role_id}`,{
        roleName:this.updateForm.roleName,
        roleDesc:this.updateForm.roleDesc
      }).then(resp=>{
        if(resp.data.meta.status !== 200) return ElMessage.error('修改失败');
        ElMessage.success('修改成功');
        this.editRoleVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //删除用户
    delDialog(row){
      this.role_id = row.id;
      this.roleName = row.roleName;
      this.delRoleVisible = true;
      console.log(row);
    },
    del(){
      this.axios.delete(`roles/${this.role_id}`).then(resp=>{
        if(resp.data.meta.status !== 200) return ElMessage.error('删除失败');
        ElMessage.success('删除成功');
        this.delRoleVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //分配角色，显示权限列表弹框
    treeDialog(row){
      this.role_id =row.id;
      this.axios.get('rights/tree').then(resp=>{
        if(resp.data.meta.status !== 200) return ElMessage.error("获取角色列表错误");
        this.treeList = resp.data.data;
      }).catch(err=>{
        console.log(err);
      })
      //接着。得到选中的这个节点的权限
      this.getNodeById(row);
      this.showTreeVisible = true;
    },
    //得到选中的节点（递归）
    getNodeById(node){
      //如果没有子节点，那就是三级节点，那么我们要的就是这个id
      if(!node.children){
        return this.checkArr.push(node.id);
      }
      //有节点的话说明还有下一级，就要开始循环直到没有下一级，循环所有子节点
      node.children.forEach(item=>{
        this.getNodeById(item);
      })
    },
    //设置分配权限
    setRoleInfo(){
      //先得到选中的节点id和半选中的节点id    ... 是ES6新特性，可以将两个数组合并成一个数组，自动解构，默认for循环得到值在放入数组
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
    ];
      //将数组通过，分割成字符串
      let keyStr = keys.join(',');
      console.log( keyStr );
      this.axios.post(`roles/${this.role_id}/rights`,{
        rids: keyStr
      }).then(resp=>{
        console.log( resp );
        if(resp.data.meta.status !== 200) return ElMessage.error('授权失败');
        ElMessage.success('授权成功');
        this.showTreeVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      });
    },
    handleClose() {
      //清空数据
      this.checkArr =[];
      this.showTreeVisible = false;
    },
    //添加角色
    addRole(formName){
      this.axios.post('roles',this.roleForm).then(resp=>{
        if(resp.data.meta.status !== 201) return ElMessage.error("创建失败");
        ElMessage.success("创建成功");
        this.resetForm(formName);
        this.addRoleVisible = false;
        this.getAllRoles();
      }).catch(err=>{
        console.log(err);
      })
    },
    //关闭表单所做的事情
    resetForm(formName){
      this.$refs[formName].resetFields();
      this.addRoleVisible = false;
    }
  }
}
</script>

<style scoped>
.el-breadcrumb{
  font-size: 20px;
}
.box-card,.el-pagination{
  margin-top: 20px;
}
.el-tag{
  margin: 10px;
}
.b_bottom{
  border-bottom: 1px solid #eee;
}
/* 上边框样式 */
.b_top{
  border-top: 1px solid #eee;
}
/* 垂直居中 */
.vcenter{
  display: flex;
  align-items: center;
}

</style>
